package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传
 * @author admin
 * @date 2024/9/29
 */
@Slf4j
@Api(tags = "通用接口")
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    // @PostMapping("/upload")
    // public Result<String> upload(MultipartFile file){
    //     log.info("文件上传:{}",file);
    //     // 获取原文件后缀名
    //     String originalFilename = file.getOriginalFilename();
    //     assert originalFilename != null;
    //     String extra = originalFilename.substring(originalFilename.lastIndexOf("."));
    //
    //     // 对文件名随机生成一个文件名
    //     String str = UUID.randomUUID().toString();
    //     String fileName = str + extra;
    //     try {
    //         String filePath = aliOssUtil.upload(file.getBytes(), fileName);
    //         return Result.success(filePath);
    //     } catch (IOException e) {
    //         e.printStackTrace();
    //     }
    //     return Result.error(MessageConstant.UPLOAD_FAILED);
    // }

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传:{}",file);
        // 生成日期路径
        try {
            String fileName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";

            FileInfo fileInfo  = fileStorageService.of(file)
                    .setPath(fileName)
                    .upload();
            return Result.success(fileInfo.getUrl());
        } catch (Exception e) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
